//
//  ViewController.m
//  myBlePeripheralDemo
//
//  Created by yorkfeng on 16/8/9.
//  Copyright © 2016年 yorkfeng. All rights reserved.
//

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>

#define UUIDSendDataService  @"0xFFE5"
#define UUIDSendDataCharateristic @"0xFFE9"
#define UUIDReadDataService  @"0xFFE0"
#define UUIDReadDataCharateristic @"0xFFE4"

@interface ViewController () <CBPeripheralManagerDelegate>

@property (strong, nonatomic) CBMutableService *service;
@property (strong, nonatomic) CBPeripheralManager *peripheralManger;
@property (strong, nonatomic) CBMutableService *customService;
@property (strong, nonatomic) CBMutableCharacteristic *customCharacteristic;
@property (strong, nonatomic) CBMutableService *customService2;
@property (strong, nonatomic) CBMutableCharacteristic *customCharacteristic2;

@property (weak, nonatomic) IBOutlet UITextField *tvName;
@property (weak, nonatomic) IBOutlet UITextField *tvSend;
@property (weak, nonatomic) IBOutlet UITextView *tvGet;
@property (weak, nonatomic) IBOutlet UITextField *tvState;

@property (strong, nonatomic) NSArray *arrCentral;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.peripheralManger=[[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupService {
    // Creates the characteristic UUID
    CBUUID *characteristicRUUID = [CBUUID UUIDWithString:UUIDReadDataCharateristic];
    // Creates the characteristic
    self.customCharacteristic = [[CBMutableCharacteristic alloc] initWithType:
                                 characteristicRUUID properties:CBCharacteristicPropertyNotify
                                                                        value:nil permissions:CBAttributePermissionsReadable];
    // Creates the service UUID
    CBUUID *serviceRUUID = [CBUUID UUIDWithString:UUIDReadDataService];
    // Creates the service and adds the characteristic to it
    self.customService = [[CBMutableService alloc] initWithType:serviceRUUID
                                                        primary:YES];
    // Sets the characteristics for this service
    [self.customService setCharacteristics:  @[self.customCharacteristic]];
    // Publishes the service
    [self.peripheralManger addService:self.customService];
    
    // Creates the characteristic UUID
    CBUUID *characteristicWUUID = [CBUUID UUIDWithString:UUIDSendDataCharateristic];
    // Creates the characteristic
    self.customCharacteristic2 = [[CBMutableCharacteristic alloc] initWithType:
                                 characteristicWUUID properties: CBCharacteristicPropertyWrite
                                                                        value:nil permissions:CBAttributePermissionsWriteable];
    // Creates the service UUID
    CBUUID *serviceWUUID = [CBUUID UUIDWithString:UUIDSendDataService];
    // Creates the service and adds the characteristic to it
    self.customService2 = [[CBMutableService alloc] initWithType:serviceWUUID
                                                        primary:YES];
    // Sets the characteristics for this service
    [self.customService2 setCharacteristics:  @[self.customCharacteristic2]];
    // Publishes the service
    [self.peripheralManger addService:self.customService2];
}

//peripheralManager状态改变
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
{
    switch (peripheral.state) {
            
        case CBPeripheralManagerStatePoweredOn:
            NSLog(@">>>设备支持BLE");
            
            [self setupService];
            
            break;
            
        default:
            NSLog(@">>>设备不支持BLE或者是未打开蓝牙");
            break;
    }
}

//perihpheral添加了service
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error {
    if (error == nil) {
        [self.peripheralManger startAdvertising:@{ CBAdvertisementDataLocalNameKey : _tvName.text, CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:UUIDSendDataService], [CBUUID UUIDWithString:UUIDReadDataService]] }];
        NSLog(@">>>开始发送advertising");
    }
}

//peripheral开始发送advertising
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
{
    if(error==nil){
        NSLog(@">>>发送advertising成功");
        [_tvState setText:@"advertising"];
    }
}

//订阅characteristics
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{
    NSLog(@"订阅了 %@的数据",characteristic.UUID);
    
    _arrCentral = [[NSArray alloc] initWithObjects:central, nil];
    
    unsigned char data[8] = {0,0,0,0,0,0,0,0};
    data[0] = 0xa5;
    data[1] = 0xc7;
    data[2] = 0x11;
    data[3] = 0x00;
    data[4] = 0x01;
    data[5] = 0x02;
    data[6] = 0x00;
    unsigned char checkSum;
    
    for (int i = 0; i < 7; i++) {
        checkSum += data[i];
    }
    
    data[7] = ~checkSum;
    
    [self.peripheralManger updateValue:[NSData dataWithBytes:data length:8] forCharacteristic:_customCharacteristic onSubscribedCentrals:_arrCentral];
    [self.peripheralManger stopAdvertising];
    [_tvState setText:@"stop"];
}

//取消订阅characteristics
-(void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic{
    NSLog(@"取消订阅 %@的数据",characteristic.UUID);
    
    [self.peripheralManger startAdvertising:@{ CBAdvertisementDataLocalNameKey : _tvName.text, CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:UUIDSendDataService], [CBUUID UUIDWithString:UUIDReadDataService]] }];
}

//读characteristics请求
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request{
    NSLog(@"didReceiveReadRequest");
    
    //判断是否有读数据的权限
    if (request.characteristic.properties & CBCharacteristicPropertyRead) {
        NSData *data = request.characteristic.value;
        [request setValue:data];
        //对请求作出成功响应
        [self.peripheralManger respondToRequest:request withResult:CBATTErrorSuccess];
    }else{
        [self.peripheralManger respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
    }
    
}

//写characteristics请求
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests{
    NSLog(@"didReceiveWriteRequests");
    CBATTRequest *request = requests[0];
    NSLog(@"requests:%@", requests);
    
    //判断是否有写数据的权限
    if (request.characteristic.properties & CBCharacteristicPropertyWrite) {
        //需要转换成CBMutableCharacteristic对象才能进行写值
        CBMutableCharacteristic *c =(CBMutableCharacteristic *)request.characteristic;
        c.value = request.value;
        [self.peripheralManger respondToRequest:request withResult:CBATTErrorSuccess];
        
        NSString *str = [[NSString alloc] initWithData:request.value  encoding:NSUTF8StringEncoding];
        str = [NSString stringWithFormat:@"%@\n%@", _tvGet.text, str];
        [_tvGet setText:str];
        
    }else{
        [self.peripheralManger respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
    }
}

- (IBAction)btnOpen:(id)sender {
    [self.peripheralManger startAdvertising:@{ CBAdvertisementDataLocalNameKey : _tvName.text, CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:UUIDReadDataService], [CBUUID UUIDWithString:UUIDSendDataService]] }];
}

- (IBAction)btnSend:(id)sender {
    [self.peripheralManger updateValue:[_tvSend.text dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:_customCharacteristic onSubscribedCentrals:_arrCentral];
}

- (IBAction)btnClose:(id)sender {
    [self.peripheralManger stopAdvertising];
    [_tvState setText:@"stop"];
}

@end
